package com.kaliterre.kalidroid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.kaliterre.kalidroid.dal.BatteryLogDAL;
import com.kaliterre.kalidroid.dal.SettingsDAL;
import com.kaliterre.kalidroid.entity.Settings;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.ToggleButton;

public class ListActivity extends Activity {
	
	private Button btnRetour;
	private ListView lvSondes;

	// Tableau contenant les noms des sondes
	String[] sondes = new String[] {
	        "Battery",
	        "Calls"
	};
	 
    // Tableau de booleens pour stocker les statuts des boutons ON/OFF
    public boolean[] status = {
        true,
        false
    };
	
    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        btnRetour=(Button)findViewById(R.id.btnRetour);
        lvSondes = (ListView) findViewById(R.id.lv_sondes);
 
        // Retrieve existing settings.
        SettingsDAL settingsDal = new SettingsDAL(lvSondes.getContext());
        settingsDal.open();
        
        Settings settings = new Settings();
        settings = settingsDal.retrieveSettings();
        settingsDal.close();
        
        // Set button state.
        if(settings.isActiveBatterySonde()) status[0] = true; else status[0] = false;
        if(settings.isActiveCallSonde()) status[1] = true; else status[1] = false;
         
        // Register listener.
        lvSondes.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> lv, View item, int position, long id) {
 
                ListView lView = (ListView) lv;
 
                SettingsDAL settingsDal = new SettingsDAL(lView.getContext());
                settingsDal.open();
                
                SimpleAdapter adapter = (SimpleAdapter) lView.getAdapter();
 
                HashMap<String,Object> hm = (HashMap) adapter.getItem(position);
                
                /** L'item selectionne dans la listView */
                RelativeLayout rLayout = (RelativeLayout) item;
 
                /** Recupere le toggle button correspondant a l'item selectionne */
                ToggleButton tgl = (ToggleButton) rLayout.getChildAt(1);
 
                String strStatus = "";
                if(tgl.isChecked()){
                    tgl.setChecked(false);
                    strStatus = "Off";
                    status[position]=false;
                    settingsDal.updateSetting(position, 0);
                }else{
                    tgl.setChecked(true);
                    strStatus = "On";
                    status[position]=true;
                    settingsDal.updateSetting(position, 1);
                }
                
                settingsDal.close();
                Toast.makeText(getBaseContext(), (String) hm.get("txt") + " : " + strStatus, Toast.LENGTH_SHORT).show();
            }
        });
        
        // Chaque ligne de la liste stocke le nom de la sonde et son statut
        List<HashMap<String,Object>> aList = new ArrayList<HashMap<String,Object>>();
 
        for(int i=0;i<sondes.length;i++){
            HashMap<String, Object> hm = new HashMap<String,Object>();
            hm.put("txt", sondes[i]);
            hm.put("stat",status[i]);
            aList.add(hm);
        }
 
        // Cles utilises dans la hashmap
        String[] from = {"txt","stat" };
 
        // Ids des vues dans listwithtoggle
        int[] to = { R.id.tv_item, R.id.tgl_status};
 
        // Instantiation de l'adapter pour stocker les items
        // R.layout.listwithtoggle defini le layout de chaque item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listwithtoggle, from, to);
 
        lvSondes.setAdapter(adapter);		
		btnRetour.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), KaliterreActivity.class);
                startActivityForResult(myIntent, 0);
            }

        });
    }

   /** 
    * Saving the current state of the activity
    * for configuration changes [ Portrait <=> Landscape ]
    */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBooleanArray("status", status);
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.list, menu);
		return true;
	}

}
